﻿
using com.iot.core.data;
using System.Data.SQLite;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace com.iot.core.util
{
    public class SqlLiteHelper
    {
        public static int ExecuteNonquery(string connStr,string sql, int CommandTimeout = 30)
        {
            using (var conn = new  SQLiteConnection(connStr))
            {
                using (var cmd = new SQLiteCommand(sql, conn))
                {
                    cmd.CommandTimeout = CommandTimeout;
                    cmd.CommandType = System.Data.CommandType.Text;
                    conn.Open();
                    return cmd.ExecuteNonQuery();
                }
            }
        }
        public static DataSet Query(string connStr, string sql,int CommandTimeout=30)
        {
            using (var conn = new SQLiteConnection(connStr))
            {
                using (var da = new SQLiteDataAdapter(sql, conn))
                {
                    da.SelectCommand.CommandTimeout = CommandTimeout;
                    var dst = new DataSet();
                    da.Fill(dst);
                    return dst;
                }

            }

        }

        public static DataTable QueryTable(string connStr, string sql, int CommandTimeout = 30)
        {
            return Query(connStr, sql, CommandTimeout).Tables[0];
        }

        public static List<T> QueryToList<T>(string connStr, string sql, int CommandTimeout = 30) where T : new()
        {
            var dt= QueryTable(connStr, sql, CommandTimeout);   
            return DataTableUtil.ToList<T>(dt);
        }
        public static List<IdNameDto> QueryName(string connstr,string tbname,List<long> lid,string namefiled="Name")
        {
            var sids = StringUtil.Join(lid);
            var sql = $"select id,{namefiled} as Name from {tbname} where id in ({sids})";
            var l = QueryToList<IdNameDto>(connstr, sql);
            return l;
        }

    }
}
